Example #1
0
        public override MemoryEntry IndirectCreateObject(MemoryEntry possibleNames)
        {
            var declarations = new HashSet <TypeValue>();

            foreach (StringValue name in possibleNames.PossibleValues)
            {
                var qualifiedName = new QualifiedName(new Name(name.Value));
                var types         = OutSet.ResolveType(qualifiedName);
                if (!types.GetEnumerator().MoveNext())
                {
                    // TODO: If no type is resolved, exception should be thrown
                    Debug.Fail("No type resolved");
                }

                declarations.UnionWith(types);
            }

            var values = new List <ObjectValue>();

            foreach (var declaration in declarations)
            {
                var newObject = CreateInitializedObject(declaration);
                values.Add(newObject);
            }

            return(new MemoryEntry(values));
        }
Example #2
0
        /// <summary>
        /// Perform logical OR operation for all combinations values in memory entries.
        /// </summary>
        /// <param name="leftOperand">The left operand of OR operation.</param>
        /// <param name="rightOperand">The right operand of OR operation.</param>
        /// <returns>Result of logical OR operation.</returns>
        public Value EvaluateOrOperation(MemoryEntry leftOperand, MemoryEntry rightOperand)
        {
            var leftBoolean = EvaluateToBoolean(leftOperand);

            if ((leftBoolean != null) && leftBoolean.Value)
            {
                return(leftBoolean);
            }
            else
            {
                var rightBoolean = EvaluateToBoolean(rightOperand);

                if ((rightBoolean != null) && rightBoolean.Value)
                {
                    return(rightBoolean);
                }
                else
                {
                    if ((leftBoolean != null) && (rightBoolean != null))
                    {
                        return(leftBoolean);
                    }
                    else
                    {
                        return(snapshot.AnyBooleanValue);
                    }
                }
            }
        }
Example #3
0
 /// <summary>
 /// Creates new instance of Constantinfo
 /// </summary>
 /// <param name="name">Constant name</param>
 /// <param name="className">Class name</param>
 /// <param name="visibility">Constant visibility</param>
 /// <param name="value">Constant value</param>
 public ConstantInfo(VariableName name, QualifiedName className, Visibility visibility, MemoryEntry value)
 {
     Name       = name;
     Value      = value;
     Visibility = visibility;
     ClassName  = className;
 }
Example #4
0
        public override MemoryEntry BinaryEx(MemoryEntry leftOperand, Operations operation, MemoryEntry rightOperand)
        {
            switch (operation)
            {
            case Operations.Equal:
                return(areEqual(leftOperand, rightOperand));

            case Operations.Add:
                return(add(leftOperand, rightOperand));

            case Operations.Sub:
                return(sub(leftOperand, rightOperand));

            case Operations.GreaterThan:
                return(gte(leftOperand, rightOperand));

            case Operations.LessThan:
                //same as GreaterThan but with inversed operands
                return(gte(rightOperand, leftOperand));

            case Operations.Or:
                return(or(leftOperand, rightOperand));

            default:
                throw new NotImplementedException();
            }
        }
Example #5
0
        private static IEnumerable <MemoryEntry> NormalizeByMinute(IEnumerable <LogEntry> logEntries)
        {
            var entriesByMinute = GetEntriesByMinute(logEntries);

            if (!entriesByMinute.Any())
            {
                yield break;
            }

            var         end       = entriesByMinute.Max(g => g.Key);
            var         currDate  = entriesByMinute.Min(g => g.Key);
            MemoryEntry lastEntry = null;

            while (currDate <= end)
            {
                if (entriesByMinute.TryGetValue(currDate, out var entry))
                {
                    lastEntry = entry;
                }

                yield return(new MemoryEntry(currDate, lastEntry.PrivateMemory, lastEntry.WorkingSet, lastEntry.GcTotalMemory));

                currDate = currDate.AddMinutes(1);
            }
        }
Example #6
0
        /// <summary>
        /// Write given value at memory represented by snapshot entry
        /// </summary>
        /// <param name="context">Context snapshot where operation is proceeded</param>
        /// <param name="value">Written value</param>
        /// <param name="forceStrongWrite">Determine that current write should be processed as strong</param>
        /// <exception cref="System.NotSupportedException">Current mode:  + snapshot.CurrentMode</exception>
        protected override void writeMemory(SnapshotBase context, MemoryEntry value, bool forceStrongWrite)
        {
            SnapshotLogger.append(context, "write memory - " + this.ToString());
            Snapshot snapshot = SnapshotEntry.ToSnapshot(context);

            switch (snapshot.CurrentMode)
            {
            case SnapshotMode.MemoryLevel:
                getTemporary(context).WriteMemory(context, value, forceStrongWrite);
                break;

            case SnapshotMode.InfoLevel:
                if (isTemporarySet(context))
                {
                    getTemporary(context).WriteMemory(context, value, forceStrongWrite);
                }
                else
                {
                    infoEntry = value;
                }
                break;

            default:
                throw new NotSupportedException("Current mode: " + snapshot.CurrentMode);
            }
        }
Example #7
0
        public void InitMemorySectionList(ProcessMap pm)
        {
            mapped_section_list.Clear();
            TotalMemorySize = 0;

            if (pm.entries == null)
            {
                return;
            }
            for (int i = 0; i < pm.entries.Length; i++)
            {
                MemoryEntry entry = pm.entries[i];
                if ((entry.prot & 0x1) == 0x1)
                {
                    ulong length   = entry.end - entry.start;
                    ulong start    = entry.start;
                    bool  isFilter = Util.SectionIsFilter(entry.name);

                    int   idx           = 0;
                    ulong buffer_length = 1024 * 1024 * 128;

                    //Executable section
                    if ((entry.prot & 0x5) == 0x5)
                    {
                        buffer_length = length;
                    }

                    while (length != 0)
                    {
                        ulong cur_length = buffer_length;

                        if (cur_length > length)
                        {
                            cur_length = length;
                            length     = 0;
                        }
                        else
                        {
                            length -= cur_length;
                        }

                        MappedSection mappedSection = new MappedSection();
                        mappedSection.Start  = start;
                        mappedSection.Length = (int)cur_length;
                        mappedSection.Name   = entry.name + "[" + idx + "]";
                        mappedSection.Check  = false;
                        mappedSection.Prot   = entry.prot;
                        mappedSection.Offset = entry.offset;
                        if (isFilter)
                        {
                            mappedSection.IsFilter = true;
                        }
                        mapped_section_list.Add(mappedSection);

                        start += cur_length;
                        ++idx;
                    }
                }
            }
        }
Example #8
0
        public override Stream GetOutputStream(string name, out IContentEntry entry)
        {
            ThrowIfObjectDisposed();
            ThrowIfObjectNotUpdating();

            MemoryEntry oldEntry;
            if (entries.TryGetValue(name, out oldEntry))
            {
                oldEntry.Dispose();

                var source = new MemoryStream();
                var memoryEntry = new MemoryEntry(name, source, DateTime.Now, true);
                entries[name] = memoryEntry;
                entry = memoryEntry;
                return memoryEntry.Source.GetOutputStream();
            }
            else
            {
                var source = new MemoryStream();
                var memoryEntry = new MemoryEntry(name, source, DateTime.Now, true);
                entry = memoryEntry;
                entries.Add(name, memoryEntry);
                return memoryEntry.Source.GetOutputStream();
            }
        }
Example #9
0
        /// <summary>
        /// Converts all possible values in memory entry to string representation.
        /// </summary>
        /// <param name="entry">Memory entry with all possible values to convert.</param>
        /// <param name="isAlwaysConcrete">Indicates whether every value converts to concrete string.</param>
        /// <returns>List of strings after conversion of all possible values.</returns>
        public IEnumerable <StringValue> Evaluate(MemoryEntry entry, out bool isAlwaysConcrete)
        {
            var values = new HashSet <StringValue>();

            isAlwaysConcrete = true;

            foreach (var value in entry.PossibleValues)
            {
                // Gets type of value and convert to string
                value.Accept(this);

                Debug.Assert((result != null) != (abstractResult != null),
                             "Result can be either concrete or abstract string value");

                if (result != null)
                {
                    values.Add(result);
                }
                else
                {
                    if (isAlwaysConcrete)
                    {
                        isAlwaysConcrete = false;
                    }
                }
            }

            return(values);
        }
Example #10
0
        /// <inheritdoc />
        protected override MemoryEntry setter(Snapshot s, MemoryEntry storedValues, MemoryEntry writtenValue)
        {
            var subResults = new HashSet <Value>();

            foreach (var value in storedValues.PossibleValues)
            {
                if (value is ObjectValue)
                {
                    continue;
                }

                if (value is UndefinedValue)
                {
                    continue;
                }

                if (value is AnyValue)
                {
                    continue;
                }

                var subResult = s.MemoryAssistant.WriteValueField(value, _field, writtenValue);
                subResults.UnionWith(subResult);
            }

            return(new MemoryEntry(subResults));
        }
Example #11
0
        /// <summary>
        /// Sets return storage to given value.
        /// </summary>
        /// <param name="flowSet">the flow set in which the return storage to be set is located</param>
        /// <param name="returnValue">the value to be set to return storage</param>
        public static void SetReturn(FlowInputSet flowSet, MemoryEntry returnValue)
        {
            var outSnapshot = flowSet.Snapshot;
            var returnVar   = outSnapshot.GetLocalControlVariable(SnapshotBase.ReturnValue);

            returnVar.WriteMemory(outSnapshot, returnValue);
        }
Example #12
0
        /// <summary>
        /// Perform logical XOR operation for all combinations values in memory entries.
        /// </summary>
        /// <param name="leftOperand">The left operand of XOR operation.</param>
        /// <param name="rightOperand">The right operand of XOR operation.</param>
        /// <returns>Result of logical XOR operation.</returns>
        public Value EvaluateXorOperation(MemoryEntry leftOperand, MemoryEntry rightOperand)
        {
            var leftBoolean  = EvaluateToBoolean(leftOperand);
            var rightBoolean = EvaluateToBoolean(rightOperand);

            if ((leftBoolean != null) && (rightBoolean != null))
            {
                if (leftBoolean.Value)
                {
                    if (rightBoolean.Value)
                    {
                        return(snapshot.CreateBool(false));
                    }
                    else
                    {
                        return(leftBoolean);
                    }
                }
                else
                {
                    return(rightBoolean);
                }
            }
            else
            {
                return(snapshot.AnyBooleanValue);
            }
        }
Example #13
0
        public override void VisitNativeAnalyzer(NativeAnalyzerPoint p)
        {
            string functionName = p.OwningPPGraph.FunctionName;

            if (nativeSanitizers.Contains(p.OwningPPGraph.FunctionName))
            {
                FunctionResolverBase.SetReturn(OutputSet, new MemoryEntry(Output.CreateInfo(false)));
                return;
            }

            // If a native function is not sanitizer, propagates taint status from arguments to return value

            // 1. Get values of arguments of the function
            // TODO: code duplication: the following code, code in SimpleFunctionResolver, and NativeFunctionAnalyzer. Move the code to some API (? FlowInputSet)
            Input.SetMode(SnapshotMode.MemoryLevel);
            MemoryEntry argc = InputSet.ReadVariable(new VariableIdentifier(".argument_count")).ReadMemory(Input);

            Input.SetMode(SnapshotMode.InfoLevel);
            int argumentCount                 = ((IntegerValue)argc.PossibleValues.ElementAt(0)).Value;
            List <MemoryEntry> arguments      = new List <MemoryEntry>();
            List <Value>       argumentValues = new List <Value>();

            for (int i = 0; i < argumentCount; i++)
            {
                arguments.Add(OutputSet.ReadVariable(Argument(i)).ReadMemory(OutputSet.Snapshot));
                argumentValues.AddRange(arguments.Last().PossibleValues);
            }

            // 2. Propagate arguments to the return value.
            FunctionResolverBase.SetReturn(OutputSet, new MemoryEntry(Output.CreateInfo(mergeTaint(argumentValues))));
        }
Example #14
0
        /// <summary>
        /// Resolve method on current snapshot entry with given methodName
        /// </summary>
        /// <param name="context">Context where methods are resolved</param>
        /// <param name="methodName">Name of resolved method</param>
        /// <returns>
        /// Resolved methods
        /// </returns>
        protected override IEnumerable <FunctionValue> resolveMethod(SnapshotBase context, PHP.Core.QualifiedName methodName)
        {
            Snapshot snapshot = SnapshotEntry.ToSnapshot(context);

            snapshot.Factories.Logger.Log(context, "resolve method - " + this.ToString() + " method: " + methodName);
            if (isTemporarySet(context))
            {
                return(getTemporary(context).ResolveMethod(context, methodName));
            }
            else
            {
                snapshot.Factories.Logger.Log(snapshot, "iterate fields: " + this.ToString());

                MemoryEntry values = readMemory(snapshot);

                snapshot.Factories.Benchmark.StartOperation(snapshot);

                snapshot.Factories.Benchmark.StartAlgorithm(snapshot, AlgorithmType.RESOLVE_METHOD);
                var methods = snapshot.Algorithms.ReadAlgorithm.GetMethod(snapshot, values, methodName);
                snapshot.Factories.Benchmark.FinishAlgorithm(snapshot, AlgorithmType.RESOLVE_METHOD);

                snapshot.Factories.Benchmark.FinishOperation(snapshot);

                return(methods);
            }
        }
Example #15
0
        private void clearDataTracker()
        {
            var previousTracker = newData.Readonly.ReadonlyChangeTracker.PreviousTracker;

            if (previousTracker != null)
            {
                List <MemoryIndex> indexes = new List <MemoryIndex>();
                CollectionMemoryUtils.AddAll(indexes, newStructure.Readonly.ReadonlyChangeTracker.IndexChanges);

                IReadOnlySnapshotData previousData = previousTracker.Container;
                foreach (MemoryIndex index in indexes)
                {
                    if (index is TemporaryIndex)
                    {
                        newStructure.Writeable.WriteableChangeTracker.RemoveIndexChange(index);
                    }
                    else
                    {
                        MemoryEntry newEntry      = getMemoryEntryOrEmpty(index, newData.Readonly);
                        MemoryEntry previousEntry = getMemoryEntryOrEmpty(index, previousData);

                        if (ValueUtils.CompareMemoryEntries(newEntry, previousEntry))
                        {
                            newData.Writeable.WriteableChangeTracker.RemoveIndexChange(index);
                        }
                    }
                }
            }
        }
Example #16
0
        public override void Include(FlowController flow, MemoryEntry includeFile)
        {
            //extend current program point as Include

            var files = new HashSet <string>();

            foreach (StringValue possibleFile in includeFile.PossibleValues)
            {
                files.Add(possibleFile.Value);
            }

            foreach (var branchKey in flow.ExtensionKeys)
            {
                if (!files.Remove(branchKey as string))
                {
                    //this include is now not resolved as possible include branch
                    flow.RemoveExtension(branchKey);
                }
            }

            foreach (var file in files)
            {
                //Create graph for every include - NOTE: we can share pp graphs
                var cfg     = AnalysisTestUtils.CreateCFG(_includes[file], null);
                var ppGraph = ProgramPointGraph.FromSource(cfg);
                flow.AddExtension(file, ppGraph, ExtensionType.ParallelInclude);
            }
        }
Example #17
0
        /// <summary>
        /// Creates the alias to this entry and returnes data which can be used to aliasing the target.
        /// </summary>
        /// <param name="snapshot">The snapshot.</param>
        /// <returns>
        /// Alias data fro the newly created aliases.
        /// </returns>
        public AliasData CreateAliasToEntry(Snapshot snapshot)
        {
            //Collect alias indexes
            AssignCollector indexesCollector = new AssignCollector(snapshot);

            indexesCollector.ProcessPath(path);

            //Memory locations where to get data from
            ReadCollector valueCollector = new ReadCollector(snapshot);

            valueCollector.ProcessPath(path);

            //Get data from locations
            ReadWorker  worker = new ReadWorker(snapshot);
            MemoryEntry value  = worker.ReadValue(valueCollector);

            //Makes deep copy of data to prevent changes after assign alias
            TemporaryIndex            temporaryIndex = snapshot.CreateTemporary();
            MergeWithinSnapshotWorker mergeWorker    = new MergeWithinSnapshotWorker(snapshot);

            mergeWorker.MergeMemoryEntry(temporaryIndex, value);

            AliasData data = new AliasData(indexesCollector.MustIndexes, indexesCollector.MayIndexes, temporaryIndex);

            data.TemporaryIndexToRealease(temporaryIndex);

            return(data);
        }
Example #18
0
        private void simplifyData()
        {
            List <MemoryIndex> indexes = new List <MemoryIndex>();

            CollectionMemoryUtils.AddAll(indexes, newData.Readonly.ReadonlyChangeTracker.IndexChanges);

            var previousTracker = newData.Readonly.ReadonlyChangeTracker.PreviousTracker;
            var currentTracker  = newData.Writeable.WriteableChangeTracker;

            foreach (MemoryIndex index in indexes)
            {
                MemoryEntry newEntry = getMemoryEntryOrEmpty(index, newData.Readonly);
                if (newEntry != null && newEntry.Count > simplifyLimit)
                {
                    MemoryEntry simplifiedEntry = assistant.Simplify(newEntry);
                    setNewMemoryEntry(index, newEntry, simplifiedEntry);

                    newEntry = simplifiedEntry;
                }

                if (previousTracker != null)
                {
                    MemoryEntry previousEntry = getMemoryEntryOrEmpty(index, previousTracker.Container);
                    if (ValueUtils.CompareMemoryEntries(previousEntry, newEntry))
                    {
                        currentTracker.RemoveIndexChange(index);
                    }
                }
            }
        }
Example #19
0
        internal void WidenWith(MemoryAssistantBase assistant)
        {
            foreach (var oldData in _oldData)
            {
                MemoryEntry widenedEntry = null;

                MemoryEntry currEntry;
                REPORT(Statistic.SimpleHashSearches);
                if (_data.TryGetValue(oldData.Key, out currEntry))
                {
                    REPORT(Statistic.MemoryEntryComparisons);
                    if (!currEntry.Equals(oldData.Value))
                    {
                        //differ in stored data
                        widenedEntry = assistant.Widen(oldData.Value, currEntry);
                    }
                }
                else
                {
                    //differ in presence of some reference
                    REPORT(Statistic.MemoryEntryCreation);
                    widenedEntry = assistant.Widen(new MemoryEntry(_owner.UndefinedValue), currEntry);
                }

                if (widenedEntry == null)
                {
                    //there is no widening
                    continue;
                }

                //apply widening
                _data[oldData.Key] = widenedEntry;
            }
        }
Example #20
0
        /// <summary>
        /// Processes the root indexes. This is the beginning of an computation which creates the root node from given sets of indexes.
        /// Used to collect all data from aliased locations.
        /// </summary>
        /// <param name="mustIndexes">The must indexes.</param>
        /// <param name="mayIndexes">The may indexes.</param>
        /// <param name="values">The values.</param>
        public void ProcessRootIndexes(HashSet <MemoryIndex> mustIndexes, HashSet <MemoryIndex> mayIndexes, IEnumerable <Value> values)
        {
            RootNode = new MemoryEntryCollectorNode();
            RootNode.SourceIndexes = new List <SourceIndex>();
            RootNode.IsMust        = true;

            foreach (MemoryIndex index in mustIndexes)
            {
                RootNode.SourceIndexes.Add(new SourceIndex(index, Snapshot));
                RootNode.CollectAliases(index, Snapshot, true);
            }
            foreach (MemoryIndex index in mayIndexes)
            {
                RootNode.SourceIndexes.Add(new SourceIndex(index, Snapshot));
                RootNode.CollectAliases(index, Snapshot, false);
            }

            RootNode.CollectValuesFromSources(this);
            RootNode.VisitValues(values);
            RootNode.CollectChildren(this);


            processQueue();
            RootMemoryEntry = RootNode.GenerateMemeoryEntry(values);
        }
Example #21
0
        private bool compareData(MemoryIndex index)
        {
            MemoryEntry newEntry = null;

            if (!newData.Readonly.TryGetMemoryEntry(index, out newEntry))
            {
                newEntry = snapshot.EmptyEntry;
            }

            MemoryEntry oldEntry = null;

            if (!oldData.Readonly.TryGetMemoryEntry(index, out oldEntry))
            {
                oldEntry = snapshot.EmptyEntry;
            }

            if (ValueUtils.CompareMemoryEntries(newEntry, oldEntry))
            {
                return(true);
            }
            else if (newEntry.Count > simplifyLimit)
            {
                MemoryEntry simplifiedEntry = assistant.Simplify(newEntry);
                MemoryEntry entry           = setNewMemoryEntry(index, newEntry, simplifiedEntry);

                return(ValueUtils.CompareMemoryEntries(entry, oldEntry));
            }
            else
            {
                return(false);
            }
        }
Example #22
0
        /// <summary>
        /// For arguments passed by reference: it assignes new values, and copies flags form inputValues.
        /// </summary>
        /// <param name="flow">FlowController</param>
        /// <param name="inputValues">Input values into analyzed function</param>
        /// <param name="nativeFunctions">Info about analyzed function</param>
        /// <returns>List of assigned values into aliases</returns>
        public static List <Value> ResolveAliasArguments(FlowController flow, List <Value> inputValues, List <NativeFunction> nativeFunctions)
        {
            List <Value> result        = new List <Value>();
            MemoryEntry  argc          = flow.InSet.ReadVariable(new VariableIdentifier(".argument_count")).ReadMemory(flow.OutSet.Snapshot);
            int          argumentCount = ((IntegerValue)argc.PossibleValues.ElementAt(0)).Value;

            foreach (var nativeFunction in nativeFunctions)
            {
                if (nativeFunction.MinArgumentCount <= argumentCount && nativeFunction.MaxArgumentCount >= argumentCount)
                {
                    int functionArgumentNumber = 0;
                    for (int i = 0; i < argumentCount; i++)
                    {
                        MemoryEntry arg = flow.InSet.ReadVariable(Argument(i)).ReadMemory(flow.InSet.Snapshot);

                        NativeFunctionArgument functionArgument = nativeFunction.Arguments.ElementAt(functionArgumentNumber);
                        if (functionArgument.ByReference == true)
                        {
                            MemoryEntry res = NativeAnalyzerUtils.ResolveReturnValue(functionArgument.Type, flow);
                            res = new MemoryEntry(FlagsHandler.CopyFlags(inputValues, res.PossibleValues));
                            flow.OutSet.GetVariable(Argument(i)).WriteMemory(flow.OutSet.Snapshot, res);
                            result.AddRange(res.PossibleValues);
                        }


                        //incremeneting functionArgumentNumber
                        if (nativeFunction.Arguments.ElementAt(functionArgumentNumber).Dots == false)
                        {
                            functionArgumentNumber++;
                        }
                    }
                }
            }
            return(result);
        }
Example #23
0
        /// <summary>
        /// Merges the memory index data.
        /// </summary>
        /// <param name="targetIndex">Index of the target.</param>
        private void mergeMemoryIndexData(MemoryIndex targetIndex)
        {
            IIndexDefinition definition;

            if (targetStructure.TryGetIndexDefinition(targetIndex, out definition))
            {
                bool valuesAlwaysDefined = collectValues(targetIndex);

                if (definition.Array != null)
                {
                    values.Add(definition.Array);
                }
                if (!valuesAlwaysDefined)
                {
                    values.Add(targetSnapshot.UndefinedValue);
                }

                MemoryEntry entry = targetSnapshot.CreateMemoryEntry(values);
                writeableTargetData.SetMemoryEntry(targetIndex, entry);

                values.Clear();
            }
            else
            {
                // Target index is not part of the structure - remove it
                writeableTargetData.RemoveMemoryEntry(targetIndex);
            }
        }
Example #24
0
        /// <summary>
        /// Collects the values.
        /// </summary>
        /// <param name="targetIndex">Index of the target.</param>
        /// <returns>true if the value is always defined</returns>
        private bool collectValues(MemoryIndex targetIndex)
        {
            bool valuesAlwaysDefined = true;

            foreach (Snapshot sourceSnapshot in sourceSnapshots)
            {
                MemoryEntry sourceEntry = getSourceEntry(targetIndex, sourceSnapshot);
                if (sourceEntry != null)
                {
                    if (sourceEntry.ContainsAssociativeArray)
                    {
                        VisitMemoryEntry(sourceEntry);
                    }
                    else
                    {
                        CollectionMemoryUtils.AddAll(values, sourceEntry.PossibleValues);
                    }
                }
                else
                {
                    valuesAlwaysDefined = false;
                }
            }

            return(valuesAlwaysDefined);
        }
Example #25
0
        /// <inheritdoc />
        public void AssignAlias(Snapshot snapshot, Memory.MemoryPath targetPath, Memory.MemoryPath sourcePath)
        {
            //Collect alias indexes
            AssignCollector sourceCollector = new AssignCollector(snapshot);

            sourceCollector.ProcessPath(sourcePath);

            //Memory locations where to get data from
            ReadCollector valueCollector = new ReadCollector(snapshot);

            valueCollector.ProcessPath(sourcePath);

            //Get data from locations
            ReadWorker  worker = new ReadWorker(snapshot);
            MemoryEntry value  = worker.ReadValue(valueCollector);

            //Makes deep copy of data to prevent changes after assign alias
            TemporaryIndex            temporaryIndex = snapshot.CreateTemporary();
            MergeWithinSnapshotWorker mergeWorker    = new MergeWithinSnapshotWorker(snapshot);

            mergeWorker.MergeMemoryEntry(temporaryIndex, value);

            //Memory locations to store data into
            AssignCollector targetCollector = new AssignCollector(snapshot);

            targetCollector.AliasesProcessing = AliasesProcessing.BeforeCollecting;
            targetCollector.ProcessPath(targetPath);

            AssignAliasWorker assignWorker = new AssignAliasWorker(snapshot);

            assignWorker.AssignAlias(sourceCollector, targetCollector, temporaryIndex);

            snapshot.ReleaseTemporary(temporaryIndex);
        }
Example #26
0
        /// <summary>
        /// Tries to get constant value from FlowOutputSet
        /// </summary>
        /// <param name="outset">FlowOutputSet which contains values</param>
        /// <param name="name">Constant name</param>
        /// <param name="entry">Memory entry of possible values</param>
        /// <returns><c>true</c> if constant is never defined, otherwise <c>true</c></returns>
        public static bool TryGetConstant(FlowOutputSet outset, QualifiedName name,
                                          out MemoryEntry entry)
        {
            var context = outset.Snapshot;
            var values  = new HashSet <Value>();

            var constantArrays = outset.ReadControlVariable(constantVariable);

            Debug.Assert(constantArrays.IsDefined(context), "Internal array of constants is always defined");

            var caseInsensitiveConstant = constantArrays.ReadIndex(context, new MemberIdentifier("." + name.Name.LowercaseValue));

            if (caseInsensitiveConstant.IsDefined(context))
            {
                entry = caseInsensitiveConstant.ReadMemory(context);
                return(false);
            }

            //else there can be case sensitive constant

            var caseSensitiveConstant = constantArrays.ReadIndex(context, new MemberIdentifier("#" + name.Name.Value));

            if (caseSensitiveConstant.IsDefined(context))
            {
                entry = caseSensitiveConstant.ReadMemory(context);
                return(false);
            }

            // Undefined constant is interpreted as a string
            var stringValue = outset.CreateString(name.Name.Value);

            entry = new MemoryEntry(stringValue);

            return(true);
        }
Example #27
0
        /// <summary>
        /// Evaluates the unary operation of all possible values in memory entry.
        /// </summary>
        /// <param name="unaryOperation">Unary operation to be performed.</param>
        /// <param name="entry">Memory entry with all possible operands of unary operation.</param>
        /// <returns>Resulting entry after performing the unary operation on all possible operands.</returns>
        public MemoryEntry Evaluate(Operations unaryOperation, MemoryEntry entry)
        {
            if ((unaryOperation == Operations.StringCast) ||
                (unaryOperation == Operations.UnicodeCast))
            {
                stringConverter.SetContext(flow);
                return(stringConverter.Evaluate(entry));
            }
            else if (unaryOperation == Operations.BoolCast)
            {
                booleanConverter.SetContext(Snapshot);
                return(new MemoryEntry(booleanConverter.Evaluate(entry)));
            }

            // Sets current operation
            operation = unaryOperation;

            var values = new HashSet <Value>();

            foreach (var value in entry.PossibleValues)
            {
                // Gets type of operand and evaluate expression for given operation
                result = null;
                value.Accept(this);

                // Returns result of unary operation
                Debug.Assert(result != null, "The result must be assigned after visiting the value");
                values.Add(result);
            }

            return(new MemoryEntry(values));
        }
Example #28
0
        /// <summary>
        /// Assigns the specified collector.
        /// </summary>
        /// <param name="collector">The collector.</param>
        /// <param name="sourceIndex">Index of the source.</param>
        internal void Assign(IIndexCollector collector, MemoryIndex sourceIndex)
        {
            foreach (MemoryIndex mustIndex in collector.MustIndexes)
            {
                snapshot.DestroyMemory(mustIndex);
                CopyWithinSnapshotWorker copyWorker = new CopyWithinSnapshotWorker(snapshot, true);
                copyWorker.Copy(sourceIndex, mustIndex);
            }

            foreach (MemoryIndex mayIndex in collector.MayIndexes)
            {
                MergeWithinSnapshotWorker mergeWorker = new MergeWithinSnapshotWorker(snapshot);
                mergeWorker.MergeIndexes(mayIndex, sourceIndex);
            }

            MemoryEntry entry = SnapshotDataUtils.GetMemoryEntry(snapshot, snapshot.CurrentData.Readonly, sourceIndex);

            LocationVisitor mustVisitor = new LocationVisitor(snapshot, entry, true);

            foreach (ValueLocation location in collector.MustLocation)
            {
                location.Accept(mustVisitor);
            }

            LocationVisitor mayVisitor = new LocationVisitor(snapshot, entry, false);

            foreach (ValueLocation location in collector.MayLocaton)
            {
                location.Accept(mayVisitor);
            }
        }
Example #29
0
        private void extendAsCallInfo(SnapshotBase callerContext, MemoryEntry thisObject, MemoryEntry[] arguments)
        {
            //TODO semantic about this object and arguments ?

            var input = callerContext as Snapshot;

            _infoData.ExtendBy(input._infoData, true);
        }
Example #30
0
        ///<inheritdoc />
        protected override MemoryEntry getter(Snapshot s, MemoryEntry storedValues)
        {
            var indexReader = new IndexReadExecutor(s.MemoryAssistant, _index);

            indexReader.VisitMemoryEntry(storedValues);

            return(new MemoryEntry(indexReader.Result));
        }
Example #31
0
 public void ImplantMemory(MemoryEntry input)
 {
     memory.SetValue(input);
 }
        public void SetResource(MadScience.Wrappers.ResourceKey key, byte[] data)
        {
            if (this.Stream.CanWrite == false)
            {
                throw new NotSupportedException();
            }

            if (this._Entries.ContainsKey(key) && this._Entries[key] is StreamEntry)
            {
                this.OriginalEntries[key] = (StreamEntry)this._Entries[key];
            }

            MemoryEntry entry = new MemoryEntry();
            entry.Compressed = false;
            entry.CompressedSize = entry.DecompressedSize = (uint)data.Length;
            entry.Data = (byte[])(data.Clone());

            this._Entries[key] = entry;
        }